#!/bin/bash
function etcd_backup(){
{% if container_manager_detected == 'containerd' %}
    ctr -n k8s.io run --rm --net-host --env ETCDCTL_API=3 \
    --mount type=bind,src=/etc/kubernetes/pki/etcd,dst=/etc/kubernetes/pki/etcd,options=rbind:ro \
    --mount type=bind,src=/etc/kubernetes/backup/etcd,dst=/etc/kubernetes/backup/etcd,options=rbind:rw \
    {{ etcd_image }} etcd-save-snapshot \
{% elif container_manager_detected == 'docker' %}
  docker run --rm --net host -e ETCDCTL_API=3 \
    -v /etc/kubernetes/backup/etcd:/etc/kubernetes/backup/etcd \
    -v /etc/kubernetes/pki/etcd/:/etc/kubernetes/pki/etcd/ \
    {{ etcd_image }} \
{% endif %}
    etcdctl snapshot save \
    /etc/kubernetes/backup/etcd/etcd-snapshot-$(date '+%Y%m%dT%H%M%S').db \
    --cacert=/etc/kubernetes/pki/etcd/ca.crt \
    --key=/etc/kubernetes/pki/etcd/healthcheck-client.key \
    --cert=/etc/kubernetes/pki/etcd/healthcheck-client.crt
}

function etcd_cleanup(){
  count=$(find /etc/kubernetes/backup/etcd -ctime +{{ etcd_backup_expiry }} -name 'etcd-snapshot*.db' | wc -l)
  if [ $count -lt {{ etcd_backup_expiry }} ]; then
    exit 0  # 备份文件数量小于备份保留天数则不进行删除；防止备份失败的情况
  fi
  find /etc/kubernetes/backup/etcd -ctime +{{ etcd_backup_expiry }} -name 'etcd-snapshot*.db' | head -n 1 | xargs rm -rf
}

case ${1} in
  backup)
    etcd_backup
    ;;
  cleanup)
    etcd_cleanup
    ;;
esac